import { Component, ElementRef, OnInit, Input, ViewChild, AfterViewInit, AfterViewChecked } from '@angular/core';
import { TreeModule, TreeNode } from 'primeng/primeng';
import { HttpClientModule, HttpClient, HttpErrorResponse } from '@angular/common/http';
import { InstitutionService } from '../services/institution.service';
import { RouterModule, Router, ActivatedRoute } from '@angular/router';
import { Service } from '../../server/server';
import { Pagination, PaginationUrl } from '../../public/serve/pcrudInfo';
import { ManagementTableComponent } from './management-table/management-table.component';
import { RemoveTableService } from '../../public/serve/remove-table/remove-table.service';
import { CudTableService } from '../../public/serve/cud-table/cud-table.service';
declare var $: any;

interface Response {
  result: string[];
  result_code: string;
  message: string;
  length: number;
}

@Component({
  selector: 'app-management',
  templateUrl: './management.component.html',
})
export class ManagementComponent implements OnInit {

  tableNumber: number = 0;

  public treeDatas: any = [];
  public selectedFiles: TreeNode[];

  right: any = {
    "user": {},
    "root_user": {}
  };

  //查询条件
  public s: any;

  constructor(
    private service: InstitutionService,
    private server: Service,
    private removeTableService: RemoveTableService,
    private tableListService: CudTableService,
    private http: HttpClient,
    public activatedRoute: ActivatedRoute,
  ) {
    this.right = $.extend(this.right, server.getRight());
  }

  public isActive = this.server.isActive;
  ngOnInit() {
    //this.getParentInfos();
    this.server.eventEmit.subscribe((value: any) => {
      this.isActive = value;
    });
    this.perstatseventEmit = this.server.perstatseventEmit.subscribe((value: any) => {
      this.opensearch = value;
    });

    this.s = {
      queryCriteria: '',
      startCreateTime: '',
      endCreateTime: '',
      startLoginTime: '',
      endLoginTime: '',
      queryType: 1,
      pageNumber: 1,
      pageSize: 20,
      id: '12aa1c87305f4271a90bffeb28315ca2'
    }
    //所属机构
    this.managementtheeventEmit = this.server.managementtheeventEmit.subscribe((value: any) => {
      //this.treeidname();
    })
  }
  //取消订阅
  public perstatseventEmit: any;
  public managementtheeventEmit: any;
  ngOnDestroy() {
    if (this.perstatseventEmit || this.managementtheeventEmit) {
      this.perstatseventEmit.unsubscribe();
      this.managementtheeventEmit.unsubscribe();
    }
  }

  ngAfterViewInit(): void {
    this.activatedRoute.queryParams.subscribe(queryParams => {
      if (queryParams.id == "add") {
        setTimeout(() => {
          this.add();
          if (document.body.offsetWidth < 1020) {
            this.server.closeindentbutton();
          }
        }, 300);
      }
    });
  }

  ngDoCheck() {
    this.right = $.extend(this.right, this.server.getRight());
    $(".ui-tree-container span:contains('已禁用')").addClass("red animate-time");
  }

  public managementtime: any;
  public opensearch: boolean;
  //最上级
  mogami() {
    //this.getParentInfos();
    this.table.getTabList(1, this.pageSize, this.superioraddId, 1, this.s.queryCriteria, this.s.startCreateTime, this.s.endCreateTime, this.s.startLoginTime, this.s.endLoginTime);
    this.superior = this.treeDatas[0].institutionName;
    this.superioraddId = this.treeDatas[0].institutionId;
    //console.log(this.superioraddId)
    //this.server.mogamieventEmit.emit(val);
  }

  //点击选中数据
  public superior: string;
  public superioraddId: string;

  public disableadd: boolean = true;
  nodeSelect(event) {
    //console.log(event.node.parentId)
    this.table.getTabList(1, this.pageSize, event.node.institutionId, 1, this.s.queryCriteria, this.s.startCreateTime, this.s.endCreateTime, this.s.startLoginTime, this.s.endLoginTime);
    //console.log(event.node.institutionId);
    if (event.node.parentId) {
      this.superior = event.node.institutionName;
      this.superioraddId = event.node.institutionId;
    }
    //禁用新增
    if (this.superior.indexOf('已禁用') >= 0) {
      this.disableadd = false;
    } else {
      this.disableadd = true;
    }
  }
  //
  msgs: any[];
  nodeUnselect(event) {
    this.msgs = [];
    this.msgs.push({ severity: 'info', summary: 'Node Unselected', detail: event.node.label });

  }
  //全部展开
  expandAll() {
    this.treeDatas.forEach(node => {
      this.expandRecursive(node, true);
    });
  }
  //全部关闭
  collapseAll() {
    this.treeDatas.forEach(node => {
      this.expandRecursive(node, false);
    });
  }
  private expandRecursive(node: TreeNode, isExpand: boolean) {
    node.expanded = isExpand;
    if (node.children) {
      node.children.forEach(childNode => {
        this.expandRecursive(childNode, isExpand);
      });
    }
  }
  //树形菜单date
  getParentInfos(): void {
    this.service.getParentInfos(null).then((data: any) => {
      this.treeDatas = data;
      this.selectedFiles = [this.treeDatas[0]];
      this.expandAll();
      //console.log(this.treeDatas);
    })
  }
  //发射id和name
  public val: any;
  treeidname() {
    //this.getParentInfos();
    if (this.treeDatas) {
      this.superior = this.superior || this.treeDatas[0].institutionName;
      this.superioraddId = this.superioraddId || this.treeDatas[0].institutionId;
      this.val = { institutionId: this.superioraddId, institutionName: this.superior }
      this.server.managementtreeidnameeventEmit.emit(this.val);
    }
  }

  //导入table
  @ViewChild("table")
  table: ManagementTableComponent;

  // 删除按钮
  isSelect: boolean = true;
  isSelectFromTableHandler(isSelect: boolean) {
    this.isSelect = isSelect;
  }

  // 禁用
  reduction() {
    setTimeout(() => {
      this.isSelect = true;
    }, 100);
  }

  // 表格
  public totalItems: number;
  ParentList(totalItems: number) {
    this.totalItems = totalItems;
  }
  //详情
  public tabVal: any;
  ParentDetails(tabVal: any) {
    this.tabVal = tabVal;
    //this.treeidname();
  }

  //新增
  public newly_added_result_code: string;
  ParentAdd(result_code: string) {
    this.table.getTabList(this.pageNumber, this.pageSize, this.superioraddId, 1, this.s.queryCriteria, this.s.startCreateTime, this.s.endCreateTime, this.s.startLoginTime, this.s.endLoginTime);
    //刷新机构树
    //this.getParentInfos();
  }
  //封装tree数据
  add() {
    $("#adminAdd").modal("show");
    //this.treeidname();
  }

  // 修改
  public edit_result_code: string;
  ParentUpdate(result_code: string) {
    this.table.getTabList(this.pageNumber, this.pageSize, this.superioraddId, 1, this.s.queryCriteria, this.s.startCreateTime, this.s.endCreateTime, this.s.startLoginTime, this.s.endLoginTime);
  }

  //删除click
  public deletes() {
    if (this.removeTableService.getRemoveTableId.length == 0) {
      this.server.prompt = { prompt: true, success: false, fail: false, promptStatement: "请选中要删除的数据!" }
      this.server.promptclose;
    } else {
      $("#delete").modal('show');
    }
  }
  //删除
  public remove_result_code: string;
  ParentDelete(result_code: string) {
    this.table.getTabList(this.pageNumber, this.pageSize, this.superioraddId, 1, this.s.queryCriteria, this.s.startCreateTime, this.s.endCreateTime, this.s.startLoginTime, this.s.endLoginTime);
    this.table.cancelSelectAll();
  }

  // 当前页（默认为第一页）
  public pageNumber: number = 1;
  // 每页显示多少条数据（默认每页显示20条）
  public pageSize: number = 20;
  // id
  public id: string = '0';
  // 分页
  public pagination: Pagination;
  isLoadTableFromPaginationHandler(pagination: Pagination) {
    this.pagination = pagination;

    this.pageNumber = this.pagination[0].pageNumber;
    this.pageSize = this.pagination[0].pageSize;
    this.id = this.pagination[0].id;

    this.tableNumber = (pagination[0].pageNumber - 1) * pagination[0].pageSize;

    this.table.getTabList(this.pageNumber, this.pageSize, this.superioraddId, 1, this.s.queryCriteria, this.s.startCreateTime, this.s.endCreateTime, this.s.startLoginTime, this.s.endLoginTime);
  }

  ParentSearch(val) {
    this.s = val;
    this.table.getTabList(
      this.pageNumber,
      this.pageSize,
      this.superioraddId,
      1,
      this.s.queryCriteria,
      this.s.startCreateTime,
      this.s.endCreateTime,
      this.s.startLoginTime,
      this.s.endLoginTime
    );
  }
  //禁用/启用
  disableEnabled(val) {
    //console.log(this.removeTableService.getRemoveTableId)
    let url = this.server.baseUrl + 'admin/pusers/modifyStatus';
    let data = {
      userId: this.removeTableService.getRemoveTableId,
      enabled: val
    }
    this.http.post<Response>(url, data, {}).subscribe(res => {
      if (res.result_code == '0000') {
        this.server.prompt = { prompt: true, success: true, fail: false, promptStatement: res.message }
        this.server.promptclose;
        this.removeTableService.getRemoveTableId = [];
        this.table.getTabList(this.pageNumber, this.pageSize, this.superioraddId, 2, this.s.queryCriteria, this.s.startCreateTime, this.s.endCreateTime, this.s.startLoginTime, this.s.endLoginTime);
        //console.log(this.superioraddId)
        //this.getParentInfos();
      } else {
        this.removeTableService.getRemoveTableId = []
        this.server.prompt = { prompt: true, success: false, fail: true, promptStatement: res.message }
        this.server.promptclose;
      }
    });
  }

}